package com.jm.common.filter;

import com.alibaba.fastjson.JSON;
import com.jm.common.util.Utils;
import com.jm.common.util.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录就访问资源
 * 属性:
 * filterName 即过滤器的名字
 * urlPatterns 表示拦截那些请求
 */
@Slf4j
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class CheckLonginFilter implements Filter {
    //    定义不被拦截的路径数组
    private static final String[] urls;


    static {
        urls = new String[]{
                "/*/login",
                "/*/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/user/login/password",
                "/images/**"
        };
    }

    //    路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

//      判断路径是否放行
        if (CheckUri(requestURI, urls)) {
            filterChain.doFilter(request, response);
            return;
        }
//        判断此次登录的类型 Attribute会在对应登陆的时候进行存放
        Object employee;
        Object admin;
        Object user;
        if ((employee = request.getSession().getAttribute("employee")) != null) {
            Long employeeId = Long.parseLong(employee.toString());
            log.info("员工{}已登录", employeeId);
//            设置记录id
            Utils.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }
        if ((admin = request.getSession().getAttribute("admin")) != null) {
            Long adminId = Long.parseLong(admin.toString());
            log.info("管理员{}已登录", adminId);
            Utils.setCurrentId(adminId);
            filterChain.doFilter(request, response);
            return;
        }
        if ((user = request.getSession().getAttribute("user")) != null) {
            Long userId = Long.parseLong(user.toString());
            log.info("用户{}已登录", userId);
            Utils.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        log.error("未登录即访问资源,请登录");
        response.getWriter().write(JSON.toJSONString(R.error("未登录即访问资源,请登录")));
    }

    /**
     * 判断请求路径是否放行
     *
     * @param requestURI 当前访问的资源路径
     * @param urls       需要放行的路径集合
     * @return 若在集合中寻找到了对应的值则表示该路径不被拦截返回true反之返回false
     */
    public boolean CheckUri(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}
